<template>
  <view class="address-add">
    <form @submit="submitForm">
      <view class="form-item">
        <text class="label">收货人</text>
        <input 
          type="text" 
          v-model="form.name" 
          placeholder="请输入收货人姓名" 
          class="input"
        />
      </view>
      
      <view class="form-item">
        <text class="label">手机号码</text>
        <input 
          type="number" 
          v-model="form.phone" 
          placeholder="请输入手机号码" 
          maxlength="11" 
          class="input"
        />
      </view>
      
      <view class="form-item">
        <text class="label">所在地区</text>
        <picker mode="multiSelector" 
          :range="[provinces, cities, districts]" 
          :range-key="'name'"
          :value="pickerValue"
          @change="onPickerChange"
          @columnchange="onColumnChange"
        >
          <view class="region-select">
            <text v-if="form.province" class="region-text">
              {{form.province + form.city + form.district}}
            </text>
            <text v-else class="placeholder">请选择所在地区</text>
            <text class="arrow">></text>
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">详细地址</text>
        <textarea 
          v-model="form.address" 
          placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等" 
          class="textarea"
        />
      </view>
      
      <view class="form-item">
        <text class="label">标签</text>
        <view class="tag-group">
          <view 
            v-for="(tag, index) in tags" 
            :key="index"
            class="tag-item"
            :class="{ active: form.tag === tag }"
            @tap="selectTag(tag)"
          >
            {{ tag }}
          </view>
        </view>
      </view>
      
      <view class="form-item switch-item">
        <text class="label">设为默认地址</text>
        <switch 
          :checked="form.isDefault" 
          @change="onDefaultChange" 
          color="#ff5500"
        />
      </view>
      
      <button 
        class="submit-btn"
        :loading="isSubmitting"
        @tap="submitForm"
      >
        保存
      </button>
    </form>
  </view>
</template>

<script>
import { regionApi } from '@/api/region'
import { addressApi } from '@/api/address'
import checkLogin from '@/mixins/checkLogin'

export default {
  mixins: [checkLogin],
  data() {
    return {
      form: {
        addressId: null,
        userId: null,
        name: '',
        phone: '',
        province: '',
        city: '',
        district: '',
        address: '',
        isDefault: false
      },
      isEdit: false,
      tags: ['家', '公司', '学校'],
      isSubmitting: false,
      // 地区选择器数据
      provinces: [],
      cities: [],
      districts: [],
      pickerValue: [0, 0, 0],
      tempRegion: null,
      indicatorStyle: 'height: 88rpx;'
    }
  },
  
  onLoad(options) {
    // 获取用户信息
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo && userInfo.id) {
      this.form.userId = userInfo.id
    } else {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        uni.navigateTo({
          url: '/pages/login/login'
        })
      }, 1500)
      return
    }

    // 如果有id参数，说明是编辑模式
    if (options.id) {
      this.isEdit = true
      this.form.addressId = options.id
      this.getAddressDetail()
    }
    // 初始化省份数据
    this.initProvinces()
  },
  
  methods: {
    // 初始化省份数据
    async initProvinces() {
      try {
        const res = await regionApi.getProvinces()
        console.log('获取省份数据:', res)
        
        if (res.code === 200) {
          this.provinces = res.data || []
          if (this.provinces.length > 0) {
            // 设置默认选中第一个省份
            this.pickerValue[0] = 0
            await this.loadCities(this.provinces[0].id)
          }
        } else {
          throw new Error(res.errorMessage || '获取省份数据失败')
        }
      } catch (error) {
        console.error('初始化省份数据失败:', error)
        uni.showToast({
          title: '加载地区数据失败',
          icon: 'none'
        })
      }
    },
    
    // 加载城市数据
    async loadCities(provinceId) {
      try {
        const res = await regionApi.getCities(provinceId)
        console.log('获取城市数据:', res)
        
        if (res.code === 200) {
          this.cities = res.data || []
          if (this.cities.length > 0) {
            // 设置默认选中第一个城市
            this.pickerValue[1] = 0
            await this.loadDistricts(this.cities[0].id)
          }
        } else {
          throw new Error(res.errorMessage || '获取城市数据失败')
        }
      } catch (error) {
        console.error('加载城市数据失败:', error)
        uni.showToast({
          title: '加载城市数据失败',
          icon: 'none'
        })
      }
    },
    
    // 加载区县数据
    async loadDistricts(cityId) {
      try {
        const res = await regionApi.getDistricts(cityId)
        console.log('获取区县数据:', res)
        
        if (res.code === 200) {
          this.districts = res.data || []
          if (this.districts.length > 0) {
            // 设置默认选中第一个区县
            this.pickerValue[2] = 0
          }
        } else {
          throw new Error(res.errorMessage || '获取区县数据失败')
        }
      } catch (error) {
        console.error('加载区县数据失败:', error)
        uni.showToast({
          title: '加载区县数据失败',
          icon: 'none'
        })
      }
    },
    
    // 处理列变化
    async onColumnChange(e) {
      const column = e.detail.column
      const value = e.detail.value
      
      try {
        if (column === 0) { // 省份改变
          const provinceId = this.provinces[value]?.id
          if (provinceId) {
            await this.loadCities(provinceId)
            this.pickerValue[1] = 0
            this.pickerValue[2] = 0
            
            // 重新加载区县
            if (this.cities.length > 0) {
              await this.loadDistricts(this.cities[0].id)
            }
          }
        } else if (column === 1) { // 城市改变
          const cityId = this.cities[value]?.id
          if (cityId) {
            await this.loadDistricts(cityId)
            this.pickerValue[2] = 0
          }
        }
      } catch (error) {
        console.error('处理列变化失败:', error)
      }
    },
    
    // 处理选择器值变化
    onPickerChange(e) {
      this.pickerValue = e.detail.value
      this.updateSelectedRegion()
    },
    
    // 更新选中的地区信息
    updateSelectedRegion() {
      const [provinceIndex, cityIndex, districtIndex] = this.pickerValue;
      
      const province = this.provinces[provinceIndex];
      const city = this.cities[cityIndex];
      const district = this.districts[districtIndex];
      
      if (province && city && district) {
        this.form.province = province.name;
        this.form.provinceId = province.id;
        this.form.city = city.name;
        this.form.cityId = city.id;
        this.form.district = district.name;
        this.form.districtId = district.id;
      }
    },
    
    // 选择标签
    selectTag(tag) {
      this.form.tag = tag
    },
    
    // 切换默认地址
    onDefaultChange(e) {
      this.form.isDefault = e.detail.value
    },
    
    // 获取地址详情
    async getAddressDetail() {
      try {
        const res = await addressApi.getAddressDetail(this.form.addressId)
        console.log('获取地址详情响应:', res)
        
        if (res.code === 200) {
          // 保存原始的userId
          const userId = this.form.userId
          
          // 将后端返回的数据映射到表单字段
          this.form = {
            userId,
            addressId: res.data.addressId,
            name: res.data.name,
            phone: res.data.phone,
            province: res.data.provinceName,
            provinceId: res.data.provinceId,
            city: res.data.cityName,
            cityId: res.data.cityId,
            district: res.data.districtName,
            districtId: res.data.districtId,
            address: res.data.detail,
            isDefault: res.data.isDefault === true,
            tag: res.data.tag
          }
          
          console.log('映射后的表单数据:', this.form)
        } else {
          throw new Error(res.msg || res.errorMessage || '获取地址详情失败')
        }
      } catch (error) {
        console.error('获取地址详情失败:', error)
        uni.showToast({
          title: error.message || '获取地址详情失败',
          icon: 'none'
        })
      }
    },
    
    // 提交表单
    async submitForm() {
      if (this.isSubmitting) return
      
      // 表单验证
      if (!this.form.name) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        })
        return
      }
      if (!this.form.phone) {
        uni.showToast({
          title: '请输入联系电话',
          icon: 'none'
        })
        return
      }
      if (!this.form.province || !this.form.city || !this.form.district) {
        uni.showToast({
          title: '请选择所在地区',
          icon: 'none'
        })
        return
      }
      if (!this.form.address) {
        uni.showToast({
          title: '请输入详细地址',
          icon: 'none'
        })
        return
      }

      try {
        this.isSubmitting = true
        let res
        
        // 构建地址数据，按后端期望的格式
        const addressData = {
          userId: this.form.userId,
          name: this.form.name,
          phone: this.form.phone,
          provinceId: this.form.provinceId,
          provinceName: this.form.province,
          cityId: this.form.cityId,
          cityName: this.form.city,
          districtId: this.form.districtId,
          districtName: this.form.district,
          detail: this.form.address,
          isDefault: this.form.isDefault,
          tag: this.form.tag
        }
        
        console.log('准备发送到后端的地址数据:', addressData)
        
        if (this.isEdit) {
          // 编辑模式需要地址ID
          addressData.addressId = this.form.addressId
          res = await addressApi.updateAddress(this.form.addressId, addressData)
        } else {
          res = await addressApi.addAddress(addressData)
        }

        console.log('后端响应:', res)

        if (res.code === 200) {
          uni.showToast({
            title: this.isEdit ? '修改成功' : '添加成功',
            icon: 'success'
          })
          
          // 如果设置为默认地址，调用设置默认地址接口
          let addressId = this.form.addressId
          if (!this.isEdit && res.data) {
            // 新增地址，从响应中获取addressId
            addressId = res.data.addressId
          }
          
          if (this.form.isDefault && addressId) {
            await this.setDefaultAddress(addressId)
          }
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error(res.msg || res.errorMessage || (this.isEdit ? '修改失败' : '添加失败'))
        }
      } catch (error) {
        console.error(this.isEdit ? '修改地址失败:' : '添加地址失败:', error)
        uni.showToast({
          title: error.message || (this.isEdit ? '修改失败' : '添加失败'),
          icon: 'none'
        })
      } finally {
        this.isSubmitting = false
      }
    },
    
    // 设置默认地址
    async setDefaultAddress(addressId) {
      if (!addressId) return
      
      try {
        const res = await addressApi.setDefaultAddress(addressId, this.form.userId)
        if (res.code !== 200) {
          console.warn('设置默认地址失败:', res.msg)
        }
      } catch (error) {
        console.error('设置默认地址失败:', error)
      }
    }
  }
}
</script>

<style lang="scss">
.address-add {
  padding: 20rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  
  .form-item {
    background-color: #fff;
    padding: 20rpx 30rpx;
    margin-bottom: 20rpx;
    border-radius: 12rpx;
    
    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 15rpx;
      display: block;
    }
    
    .input {
      width: 100%;
      height: 80rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    .textarea {
      width: 100%;
      height: 160rpx;
      font-size: 28rpx;
      color: #333;
    }
    
    .region-select {
      height: 88rpx;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 20rpx;
      background-color: #f8f8f8;
      border-radius: 8rpx;
      
      .region-text {
        font-size: 28rpx;
        color: #333;
      }
      
      .placeholder {
        font-size: 28rpx;
        color: #999;
      }
      
      .arrow {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    &.switch-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .label {
        margin-bottom: 0;
      }
    }
  }
  
  .tag-group {
    display: flex;
    flex-wrap: wrap;
    margin-top: 10rpx;
    
    .tag-item {
      padding: 10rpx 30rpx;
      border: 1rpx solid #ddd;
      border-radius: 30rpx;
      margin-right: 20rpx;
      margin-bottom: 20rpx;
      font-size: 24rpx;
      color: #666;
      
      &.active {
        color: #ff5500;
        border-color: #ff5500;
        background-color: #fff5f0;
      }
    }
  }
  
  .submit-btn {
    width: 90%;
    height: 90rpx;
    line-height: 90rpx;
    background: linear-gradient(to right, #ff7500, #ff5500);
    color: #fff;
    font-size: 32rpx;
    border-radius: 45rpx;
    margin-top: 60rpx;
    
    &:disabled {
      opacity: 0.6;
    }
  }
}
</style> 